package com.bckj.fastboot.core.extra.i18n;

import com.bckj.fastboot.core.redis.RedisOps;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

/**
 * 资源文件配置加载
 * 
 * @author ruoyi
 */
@AutoConfiguration
public class FastI18nConfiguration implements WebMvcConfigurer
{
    @Bean
    public LocaleResolver localeResolver()
    {
        SessionLocaleResolver slr = new SessionLocaleResolver();
        // 默认语言
        slr.setDefaultLocale(Locale.CHINA);
        return slr;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor()
    {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        // 参数名
        lci.setParamName("lang");
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry)
    {
        registry.addInterceptor(localeChangeInterceptor());
    }

    /**
     * 创建并配置国际化消息源
     * @return 可重载的资源包消息源
     */
    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:i18n/messages");
        return messageSource;
    }

    @Bean
    @ConditionalOnBean(RedisOps.class)
    @ConditionalOnMissingBean(I18nMessageRepository.class)
    public I18nMessageRepository defaultI18nMessageRepository(RedisOps redisOps) {
        return new DefaultI18nMessageRepository(redisOps);
    }

    @Bean
    @ConditionalOnBean(I18nMessageRepository.class)
    public FastMessageSource fastMessageSource(I18nMessageRepository i18nMessageRepository) {
        return new FastMessageSource(messageSource(), i18nMessageRepository);
    }
}
